﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using YArchitech.Revit;

namespace YJKRGeometry
{
	public class DataSerializeDeserialize
	{
		public static bool PointToString(XYZ point, out string pointString)
		{
			bool result;
			try
			{
				pointString = point.ToString();
				result = true;
			}
			catch
			{
				pointString = "";
				result = false;
			}
			return result;
		}

		public static bool StringToPoint(string pointString, out XYZ point)
		{
			bool result;
			try
			{
				pointString = pointString.Substring(1, pointString.Length - 2);
				string[] array = pointString.Split(new char[]
				{
					','
				});
				point = new XYZ(Convert.ToDouble(array[0]), Convert.ToDouble(array[1]), Convert.ToDouble(array[2]));
				result = true;
			}
			catch
			{
				point = null;
				result = false;
			}
			return result;
		}

		public static bool LineToString(Line line, out string lineString)
		{
			bool result;
			try
			{
				lineString = "Line:" + line.GetEndPoint(0).ToString() + ":" + line.GetEndPoint(1).ToString();
				result = true;
			}
			catch
			{
				lineString = "";
				result = false;
			}
			return result;
		}

		public static bool StringToLine(Document doc, string lineString, out Line line, bool isBound = true)
		{
			bool result;
			try
			{
				lineString = lineString.Substring(0, lineString.Length - 2);
				string[] array = lineString.Split(new char[]
				{
					':'
				});
				if (array[0] == "Line")
				{
					XYZ point = null;
					XYZ endOrDirection = null;
					DataSerializeDeserialize.StringToPoint(array[1], out point);
					DataSerializeDeserialize.StringToPoint(array[2], out endOrDirection);
					if (isBound)
					{
						line = doc.CreatYJKLine(point, endOrDirection, true);
					}
					else
					{
						line = doc.CreatYJKLine(point, endOrDirection, false);
					}
					result = true;
				}
				else
				{
					line = null;
					result = false;
				}
			}
			catch
			{
				line = null;
				result = false;
			}
			return result;
		}

		public static bool LineToString(List<Line> lstLine, out List<string> lstLineString)
		{
			lstLineString = new List<string>();
			bool result;
			try
			{
				string item = "";
				foreach (Line line in lstLine)
				{
					DataSerializeDeserialize.LineToString(line, out item);
					lstLineString.Add(item);
				}
				result = true;
			}
			catch
			{
				lstLineString = null;
				result = false;
			}
			return result;
		}

		public static bool StringToLine(Document doc, List<string> lstLineString, out List<Line> lstLine, bool isBound = true)
		{
			lstLine = new List<Line>();
			bool result;
			try
			{
				Line item = null;
				foreach (string lineString in lstLineString)
				{
					DataSerializeDeserialize.StringToLine(doc, lineString, out item, isBound);
					lstLine.Add(item);
				}
				result = true;
			}
			catch
			{
				lstLine = null;
				result = false;
			}
			return result;
		}
	}
}
